package com.heima.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生成者
 */
public class ProducerQuickStart {
    public static void main(String[] args) {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.88.2:9092");
        //发送失败，失败的[重试次数]
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息确认机制
        //ACKS=1(默认): 只要[集群首领]节点收到消息，生产者就会收到一个来自服务器的成功响应
        //ACKS=0: 生产者在成功写入消息之前不会等待任何来自服务器的响应,消息有丢失的风险，但是速度最快
        //ACKS=all: 只有当[所有参与赋值的节点]全部收到消息时，生产者才会收到一个来自服务器的成功响应
        properties.put(ProducerConfig.ACKS_CONFIG,"1");
        //消息压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");
        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        //封装发送的消息
        //ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic",0,"100001","hello kafka");
        for (int i = 0; i <5; i++) {
            ProducerRecord<String, String> helloKafka = new ProducerRecord<>("itcast-topic-input", "hello kafka");
            producer.send(helloKafka);
        }
        //    try {
//        //3.发送消息,同步发送，发送成功返回偏移量
//        RecordMetadata recordMetadata = producer.send(record).get();
//        System.out.println(recordMetadata.offset());
//    } catch (Exception e) {
//        e.printStackTrace();
//    }
//        //异步发送
//        producer.send(record,new Callback() {
//
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                if (e != null) {
//                    System.out.println("记录异常信息为:");
//                    e.printStackTrace();
//                }
//                System.out.println(recordMetadata.offset());
//            }
//        });
        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }
    }
